import 'package:http/http.dart' as http;
import 'dart:convert';

class Client {
  static const HOST = "http://wxapp.qqvbc.com/";

  static Future<String> get(String url, {Map<String, String> params}) async {
    http.Response response;

    String p = "";

    if (params != null) {
      params.forEach((k, v) {
        p = "&" + p + k + "=" + v;
      });
    }

    String newUrl = url.contains("?") ? url + p : url + "?" + p;

    try {
      response = await http.get(_url(newUrl));
    } catch (e) {
      throw "net request error: " + e.toString();
    }

    if (response.statusCode == 200) {
      var s = response.body;
      return s;
    } else {
      throw "response error, status code:" + response.statusCode.toString();
    }
  }

  static Future<String> post(String url, {Map<String, String> params}) async {
    http.Response response;

    try {
      response = await http.post(_url(url), body: params);
      print("post params");
      print(params);
    } catch (e) {
      throw e;
//      throw "net request error: " + e.toString();
    }

    if (response.statusCode == 200) {
      var s = response.body;
      return s;
    } else {
      throw "response error, status code:" + response.statusCode.toString();
    }
  }

  static String _url(String url) {
    String newUrl;
    if (url.contains("http://") || url.contains("https://")) {
      newUrl = url;
    } else {
      newUrl = HOST + url;
    }

    print("client url " + newUrl);
    return newUrl;
  }
}
